#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
__version__ = '1.0'
"""
    ***********************************
    *  @filename : user.py
    *  @Author : wshu
    *  @CodeDate : 2020/3/25 14:21
    *  @Software : PyCharm
    ***********************************
"""
import tornado.gen
import tornado.web
from core import BaseHandlers
from Ui.HFmSetting.utils.functional import paging
from core.comm.http.JsonResponse import Jsonify, JsonForm
from db.mysql import User
from sqlalchemy import func, and_, or_, desc
from Ui.HFmSetting.utils.checktool import checkemail, checkpsd, check_username
from core.auth.hashers import make_password


class AddUserHandler(BaseHandlers):
    """
    用户添加
    """
    error_msg = ''

    def get(self, *args, **kwargs):
        self.render('users/user_add.html', error_msg=self.error_msg)

    def post(self, *args, **kwargs):
        """
        添加用户，目前无权限划分
        """
        realname = self.get_argument('name')
        username = self.get_argument('username')
        jobname = self.get_argument('jobname')
        telphone = self.get_argument('phone')
        email = self.get_argument('email')
        password = self.get_argument('pass')
        re_password = self.get_argument('repass')
        if check_username(username):
            if password == re_password:
                if checkemail(email):
                    if checkpsd(password):
                        user_get = self.db.query(User).filter_by(username=username).first()
                        if user_get:
                            self.error_msg = '添加失败，该用户已存在'
                        else:
                            create_user_obj = User(
                                username=username,
                                password=make_password(password),
                                is_superuser=False,
                                is_active=True,
                                realname=realname,
                                job_title=jobname,
                                telphone=telphone,
                                email=email)
                            self.db.add(create_user_obj)
                            self.db.commit()
                            self.error_msg = '添加成功'
                    else:
                        self.error_msg = '密码必须6位且字符加数字组合'
                else:
                    self.error_msg = '请检查邮箱格式是否正确'
            else:
                self.error_msg = '请检查，两次输入的密码不一致'
        else:
            self.error_msg = '请检查输入，用户名不合法'
        self.write('ok')

class UserViewHandler(BaseHandlers):
    """
    用户视图
    """
    error_msg = ''
    def get(self, *args, **kwargs):
        self.render('users/user_list.html', error_msg=self.error_msg)

    def post(self, *args, **kwargs):
        self.write('ok')



class UserListHandler(BaseHandlers):
    """
    用户列表
    """
    error_msg = ''

    def check_xsrf_cookie(self):
        # 非常有用的在单页面禁用xsrf_cookie的检查
        return True

    @staticmethod
    def get_count(Q):
        count_query = Q.statement.with_only_columns([func.count()]).order_by(None)
        count = Q.session.execute(count_query).scalar()
        return count

    def post(self, *args, **kwargs):
        page = self.get_argument('page', None)
        rows = self.get_argument('limit', None)
        username = self.get_argument('uname', None)
        is_active = self.get_argument('is_active', None)

        if not username:
            username = ''

        if not is_active:
            is_active = ['True', 'False']
        else:
            is_active = [is_active]

        # 分页查询 p: 页 r: 条
        p, r = paging(page, rows)
        # 查询已激活的用户
        user_obj = self.db.query(User).filter(or_(User.username.like(username),
                                                  User.is_active.notin_(is_active)))
        user_list = user_obj.order_by(desc(User.date_joined)).slice(p, r).all()
        total = self.get_count(user_obj)
        laydata = []
        for user_item in user_list:
            tempDict = {}
            tempDict['name'] = user_item.realname
            tempDict['username'] = user_item.username
            tempDict['email'] = user_item.email
            tempDict['date'] = user_item.date_joined.strftime("%Y-%m-%d %H:%M:%S")
            tempDict['title'] = user_item.job_title
            if user_item.is_active:
                tempDict['status'] = '启用'
            else:
                tempDict['status'] = '禁用'

            laydata.append(tempDict)

        # 以JSON形式返回数据
        json_data = Jsonify(
            code=0,
            msg="用户列表",
            count=total,
            data=laydata).json()
        self.write(json_data)


class UserInfoHandler(BaseHandlers):
    """
    用户信息
    """
    error_msg = ''

    def get(self, *args, **kwargs):
        user = self.get_current_user()
        if user:
            current_user = user.decode('utf-8')
            user_get = self.db.query(User).filter(User.username == current_user).first()
            realname = user_get.realname
            email = user_get.email
            username = user_get.username
            job_title = user_get.job_title
            date_joined = user_get.date_joined
            telphone = user_get.telphone
            description = user_get.description
            self.render('users/user_info.html', error_msg=self.error_msg,
                        realname=realname, username=username, job_title=job_title, email=email,
                        date_joined=date_joined, telphone=telphone, description=description)
        else:
            self.render('users/user_info.html', error_msg=self.error_msg)

class ChangePwdHandler(BaseHandlers):
    """
    修改密码
    """
    error_msg = ''

    def get(self, *args, **kwargs):
        self.render('users/user_edit.html', error_msg=self.error_msg)

    def post(self, *args, **kwargs):
        user = self.get_current_user()
        if user:
            current_user = user.decode('utf-8')
            newpwd = self.get_argument('newpass')
            repwd = self.get_argument('repass')
            if newpwd == repwd:
                if checkpsd(repwd):
                    self.db.query(User).filter(User.username == current_user).update({User.password: make_password(repwd)})
                    self.db.commit()
                    self.error_msg = JsonForm(status='success', msg='操作成功，密码已修改，请重新登录').Dict
                    # self.redirect('/signin')
                    # raise tornado.web.Finish
                else:
                    self.error_msg = JsonForm(status='error', msg='密码必须6位且字符加数字组合').Dict
            else:
                self.error_msg = JsonForm(status='error', msg='两次输入的密码不一致').Dict
        else:
            self.error_msg = JsonForm(status='error', msg='操作失败').Dict
        self.write(self.error_msg)

class DisableUserHandler(BaseHandlers):
    """
    停用用户
    """

class EnableUserHandler(BaseHandlers):
    """
    启用用户
    """